package com.itheima.user.service.impl;

import com.itheima.model.common.dtos.ResponseResult;
import com.itheima.model.common.enums.AppHttpCodeEnum;
import com.itheima.model.user.dtos.SignDto;
import com.itheima.model.user.pojos.Sign;
import com.itheima.model.user.pojos.User;
import com.itheima.utils.thread.MpThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SignServiceImpl {

    @Autowired
    private MongoTemplate mongoTemplate; // 使用MongoTemplate操作MongoDB

    /**
     * 获取用户签到数据
     * @return 包含用户签到信息的响应结果
     */
    public ResponseResult getSignData() {
        // 1. 获取当前登录用户
        User user = MpThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
            // 2. 构建查询条件：按用户ID查询
            Query query = Query.query(Criteria.where("user_id").is(user.getId()));

            // 3. 执行查询
            Sign sign = mongoTemplate.findOne(query, Sign.class);

            // 4. 返回结果（若未签到过，返回空对象而非null，避免前端处理异常）
            return ResponseResult.okResult(sign != null ? sign : new Sign());
        } catch (Exception e) {
            log.error("获取用户签到数据失败", e);
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "获取签到数据失败");
        }
    }

    /**
     * 保存用户签到数据（新增或更新）
     * @param dto 签到数据DTO
     * @return 操作结果
     */
    public ResponseResult saveSignData(SignDto dto) {
        // 1. 校验参数和登录状态
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        User user = MpThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            // 2. 构建Sign实体（从DTO复制属性）
            Sign sign = new Sign();
            BeanUtils.copyProperties(dto, sign);
            // 确保用户ID与当前登录用户一致（防止篡改）
            sign.setUserId(user.getId());

            // 3. 执行保存（MongoDB会根据ID自动判断新增或更新）
            mongoTemplate.save(sign);

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.error("保存用户签到数据失败", e);
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "保存签到数据失败");
        }
    }
}